package com.tom.architect.party4.day34.retrofit;

import android.util.Log;
import java.io.IOException;

public class OkHttpCall<T> implements Call<T> {
    final ServiceMethod serviceMethod; // 方法
    final Object[] args; // 方法的参数

    public OkHttpCall(ServiceMethod serviceMethod, Object[] args) {
        this.serviceMethod = serviceMethod;
        this.args = args;
    }

    @Override
    public void enqueue(Callback<T> callback) {
        // 正式的 发起请求。然后给一个回调
        // Log.e("TAG", "enqueue: 正式的 发起请求。");
        okhttp3.Call call = serviceMethod.createNewCall(args);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                if (callback != null) {
                    callback.onFailure(OkHttpCall.this, e);
                }
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                // 解析： Response -> Response<T> ，然后回调
                // Log.e("TAG",response.body().string());
                // 涉及到数据的解析，不能在这里写死，ConvertFactory
                Response rResponse = new Response();
                rResponse.body = serviceMethod.parseBody(response.body());
                if (callback != null) {
                    // 回调回去。
                    callback.onResponse(OkHttpCall.this, rResponse);
                }
            }
        });
    }

}
